<?php

namespace App\Jobs;

use App\Datalog\Events\PayEventLog;
use App\Datalog\Users\PayUserSet;
use App\Models\Orders;
use App\Models\UserExtend;
use App\Services\AdPostbackService;
use App\Services\PayService;
use App\Services\UserExtendService;
use App\Services\UserRoleService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class PaySuccessQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    use TraitQueue;

    protected $tradeNo;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($trade_no)
    {
        $this->tradeNo = $trade_no;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $order = Orders::where('trade_no', $this->tradeNo)->first();

        // 数据落地
        PayEventLog::getInstance()->addLog($order);

        // 更新用户扩展表
        UserExtendService::getInstance()->paySuccess($order);

        // 更新角色表
        UserRoleService::getInstance()->paySuccess($order->user_id, $order->server_id, $order->role_id, $order->create_time, $order->money);

        // userset
        $extend = UserExtendService::getInstance()->getOrCreate($order->user_id);
        PayUserSet::getInstance()->addSet($extend);

        // 进行一次买量回传
        AdPostbackService::getInstance()->postbackPay($order);
    }
}
